package com.joven.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.joven.core.mapper.TblGoodsStoreMapper;
import com.joven.core.model.TblGoodsStore;
import com.joven.core.service.TestRedisLockService;
import com.joven.core.utils.lockUtil.RedisTempDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author joven_wong
 * @since 2021/7/1 16:08
 */
@Service
public class TestRedisLockServiceImpl implements TestRedisLockService {

    @Autowired
    RedisTempDistributedLock redisTempDistributedLock;
    @Autowired
    TblGoodsStoreMapper tblGoodsStoreMapper;

    private static final int TIMEOUT = 5*1000;//5s

    @Override
    public String updateCountCore(String countNo, int num) {
        String result;
        //上锁
        long time = System.currentTimeMillis() + TIMEOUT;
        if (!redisTempDistributedLock.lock(countNo, String.valueOf(time))) {
            result = "wait";
            return result;
        }
        System.out.println("获得锁的时间戳：" + time);
        try {
            QueryWrapper<TblGoodsStore> wrapper = new QueryWrapper<>();
            wrapper.eq(TblGoodsStore.ACCOUNT_NO, countNo);
            TblGoodsStore goodsStore = tblGoodsStoreMapper.selectOne(wrapper);
            if (goodsStore != null) {
                int storeNum = goodsStore.getStoreNum();
                if (storeNum <= 0) {
                    return "false";
                }
                if (storeNum < num) {
                    return "sorry";
                }
                System.out.println("库存：" + storeNum + "扣除库存：" + num);
                UpdateWrapper<TblGoodsStore> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq(TblGoodsStore.ACCOUNT_NO, countNo).set(TblGoodsStore.STORE_NUM, storeNum - num);
                //            updateWrapper.eq(TblGoodsStore::getAccountNo, countNo).set(TblGoodsStore::getStoreNum, storeNum-num);
                Integer rows = tblGoodsStoreMapper.update(null, updateWrapper);
                try {
                    //为了更好的测试多线程同时进行库存扣减，在进行数据更新之后先等2秒，让多个线程同时竞争资源
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "success";

            } else {
                return "false";
            }
        } finally {
            //释放锁
            redisTempDistributedLock.release(countNo, String.valueOf(time));
            System.out.println("释放锁的时间戳："+time);
        }
    }
}
